package com.hkd.blogsystem.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtils {
    private static final long expiration= 30 * 60 * 1000;//过期时间
    private static String SecretSting = "W1yaFu94uDM0CWMP0fomM6uYeI7RRKIP1BTb3SIkXqE=";//秘钥
    private static Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(SecretSting));

    /**
     * 生成令牌
     * @param claims
     * @return
     */

    public static String genJwt(Map<String,Object> claims){
        /*Map<String,Object> data = new HashMap<>();
        data.put("id",5);
        data.put("name","zhangsan");*/

        String compact = Jwts.builder().setClaims(claims).
                setExpiration(new Date(System.currentTimeMillis()+expiration)).signWith(key).compact();//生成令牌
        return compact;
    }
    /*void genKey(){ //生成秘钥
        SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);//生成加密
        String encode = Encoders.BASE64.encode(secretKey.getEncoded());
        System.out.println(encode);
    }*/

    /**
     * 校验
     * @param token
     * @return
     */
    public static Claims verify(String token ){
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims calsms = null;
        try{
            calsms = build.parseClaimsJws(token).getBody();
        }catch (Exception e){
        log.error("token校验失败，token:"+token +",e:{"+ e + "}");
        }

        return calsms;
    }

    public static Integer getUserIdFromToken(String token){
        Claims claims = verify(token);
        Assert.notNull(claims, "token不合法");
        Integer userId = (Integer) claims.get("id");
        return userId;
    }

}

